package cn.monkey.family.server.domain.uc.resource;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.uc.resource.Resource;
import cn.monkey.family.data.uc.resource.ResourceQueryRequest;
import cn.monkey.family.data.uc.resource.ResourceVo;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("resource")
public class ResourceController {
    protected final IResourceService resourceService;

    public ResourceController(IResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @GetMapping({"{id}", ""})
    Result<?> get(@Context RequestContext requestContext,
                  @PathVariable(value = "id", required = false) String id,
                  ResourceQueryRequest queryRequest,
                  @RequestParam(value = "action", required = false) String action,
                  @RequestParam(value = "maxDeep", defaultValue = "-1") Integer maxDeep,
                  @PageableDefault Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.resourceService.readById(requestContext, id);
        }
        if ("tree".equals(action)) {
            return this.resourceService.getMenuTree(requestContext, queryRequest, pageable.getSort(), maxDeep);
        }
        return this.resourceService.readPage(requestContext, queryRequest, pageable);
    }

    @PostMapping
    Result<ResourceVo> create(@Context RequestContext requestContext,
                              @RequestBody Resource resource) {
        return this.resourceService.create(requestContext, resource);
    }

    @PutMapping("{id}")
    Result<ResourceVo> update(@Context RequestContext requestContext,
                              @PathVariable String id,
                              @RequestBody Resource resource) {
        return this.resourceService.update(requestContext, id, resource);
    }

    @DeleteMapping("{id}")
    Result<Void> delete(@Context RequestContext requestContext,
                        @PathVariable String id) {
        return this.resourceService.delete(requestContext, id);
    }
}
